/* Copyright (c) 2009, Antonie Jovanoski
 *	
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contact e-mail: Antonie Jovanoski <minimoog77@gmail.com>
 */

#include <QMessageBox>
#include "mainwindow.h"
#include "userpassdialog.h"
#include "qtwitverifycredentials.h"
#include "shortenedurl.h"

MainWindow::MainWindow()
:	m_twitFriendsTimeline(new QTwitFriendsTimeline(this)),
	m_twitUpdate(new QTwitUpdate(this)),
	m_twitDestroy(new QTwitDestroy(this)),
	m_imageDownloader(new ImageDownloader(this)),
	m_timer(new QTimer(this))
{
	ui.setupUi(this);
	ui.groupWidget->hide();
	ui.updateEdit->setLimit(140);
	ui.twitsWidget->setImageDownloader(m_imageDownloader);

	QSettings settings("QTwitdget", "QTwitdget");
	m_username = settings.value("LastUsername").toString();

	m_maxStatuses = 200;
	m_initialUpdate = true;

	connect(ui.updateButton, SIGNAL(clicked()), SLOT(updateButtonClicked()));
	connect(m_twitFriendsTimeline, SIGNAL(finished()), SLOT(finishedFriendsTimeline()));
	connect(ui.updateEdit, SIGNAL(overLimit(bool)), ui.updateButton, SLOT(setDisabled(bool)));
	connect(ui.updateEdit, SIGNAL(returnPressed()), ui.updateButton, SLOT(click()));
	connect(ui.twitsWidget, SIGNAL(requestReplyStatus(const QString&, int)), 
			m_twitUpdate, SLOT(setUpdate(const QString&, int)));
	connect(m_twitDestroy, SIGNAL(destroyed(int)), SLOT(statusDestroyed(int)));
	connect(ui.twitsWidget, SIGNAL(requestDeleteStatus(int)), m_twitDestroy, SLOT(deleteStatus(int)));

	connect(ui.actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
	connect(ui.actionCnangeUser, SIGNAL(triggered()), SLOT(userpass()));

	setupTrayIcon();

	userpass();
}

void MainWindow::userpass()
{
	UserPassDialog upd(this);
	upd.setUsername(m_username);

	if(!m_username.isEmpty())
		upd.setPasswordEditFocut();

	if(QDialog::Accepted == upd.exec()){
		QTwitVerifyCredentials *vc = new QTwitVerifyCredentials;

		connect(vc, SIGNAL(finished(bool)), SLOT(finishedVerifying(bool)));
		vc->setUsername(upd.username());
		vc->setPassword(upd.password());
		m_verified = false;
		vc->verify();

		//block until is verified
		while(!m_verified)
			qApp->processEvents();

		if(!m_userpassValid){
			delete vc;
			QMessageBox::warning(this, tr("Invalid credentials"), tr("Username or password invalid"));
			return;
		}

		delete vc;

		setUserPass(upd.username(), upd.password());

		//store last used username
		QSettings settings("QTwitdget", "QTwitdget");
		settings.setValue("LastUsername", upd.username());

		//start update timer
		connect(m_timer, SIGNAL(timeout()), SLOT(updateTimeline()));
		m_timer->start(60000);

		updateTimeline();
	}
}

void MainWindow::setUserPass(const QString &username, const QString &password)
{
	m_twitFriendsTimeline->setUsername(username);
	m_twitFriendsTimeline->setPassword(password);
	m_twitUpdate->setUsername(username);
	m_twitUpdate->setPassword(password);
	m_twitDestroy->setUsername(username);
	m_twitDestroy->setPassword(password);
	ui.twitsWidget->setUsername(username);
	m_username = username;
	m_password = password;
}

void MainWindow::updateTimeline()
{
	if(m_initialUpdate) //first update
		m_twitFriendsTimeline->update(QDateTime(), 0, 200, 0);
	else
		//get statuses more recent than last status 
		m_twitFriendsTimeline->update(QDateTime(), m_statuses.at(0).id(), 0, 0);
}

void MainWindow::updateButtonClicked()
{
	if(!ui.updateEdit->toPlainText().isEmpty()){
		//trim to 140 characters
		QString updateText = ui.updateEdit->toPlainText().left(140);
		m_twitUpdate->setUpdate(updateText);
		ui.updateEdit->clear();
	}
}

void MainWindow::finishedFriendsTimeline()
{
	QList<QTwitStatus> lastStatuses = m_twitFriendsTimeline->getStatuses();

	if(lastStatuses.isEmpty())
		return;

	QListIterator<QTwitStatus> iter(lastStatuses);
	iter.toBack();
	while(iter.hasPrevious())
		m_statuses.prepend(iter.previous());

	//update status widgets
	ui.twitsWidget->setStatuses(m_statuses);
	ui.twitsWidget->updateStatusWidgets();

	m_initialUpdate = false;
}

void MainWindow::finishedVerifying(bool valid)
{
	m_userpassValid = valid;
	m_verified = true;
}

void MainWindow::statusDestroyed(int id)
{
	QMutableListIterator<QTwitStatus> i(m_statuses);
	while(i.hasNext()){
		QTwitStatus ts = i.next();
		if(ts.id() == id){
			i.remove();
			break;
		}
	}

	//update
	ui.twitsWidget->setStatuses(m_statuses);
	ui.twitsWidget->updateStatusWidgets();
}

void MainWindow::setupTrayIcon()
{
	connect(ui.actionQuit, SIGNAL(triggered()), qApp, SLOT(quit()));

	m_trayIconMenu = new QMenu(this);
	m_trayIconMenu->addAction(ui.actionMinimize);
	m_trayIconMenu->addAction(ui.actionRestore);
	m_trayIconMenu->addSeparator();
	m_trayIconMenu->addAction(ui.actionQuit);

	m_trayIcon = new QSystemTrayIcon(this);
	m_trayIcon->setIcon(QIcon(":/images/twitter_32.ico"));
	m_trayIcon->setContextMenu(m_trayIconMenu);
	m_trayIcon->show();

	connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
		SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
}

void MainWindow::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
	switch(reason){
		case QSystemTrayIcon::Trigger:
		case QSystemTrayIcon::DoubleClick:
			showNormal();
			break;
		default:
			;
	}
}

void MainWindow::closeEvent(QCloseEvent *e)
{
	hide();
	e->ignore();
}